<template>
	<el-card class="full-card">
		<div class="stock-product">
			<!-- 查询表单 -->
			<el-form :model="searchForm" :inline="true" class="search-form">
				<el-form-item label="商品码">
					<el-input
						v-model="searchForm.itemCode"
						placeholder="请输入商品码"
						clearable
						@keyup.enter="handleSearch"
					/>
				</el-form-item>
				<el-form-item label="条形码">
					<el-input
						v-model="searchForm.barcode"
						placeholder="请输入条形码"
						clearable
						@keyup.enter="handleSearch"
					/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleSearch">
						<el-icon><search /></el-icon>
						查询
					</el-button>
					<el-button @click="handleReset">重置</el-button>
					<el-button type="primary" @click="handleRefresh">
						<el-icon><refresh /></el-icon>
						刷新
					</el-button>
				</el-form-item>
			</el-form>

			<div>
				<el-button type="primary" @click="exportData" :loading="exportLoading">
					导出
				</el-button>
			</div>

			<!-- 数据表格 -->
			<el-table
				border
				v-loading="loading"
				:data="tableData"
				style="width: 100%; margin-top: 20px"
				@selection-change="handleSelectionChange"
			>
				<el-table-column type="selection" width="55" />
				<el-table-column prop="itemCode" label="商品码" min-width="140" />
				<el-table-column prop="barcode" label="条形码" min-width="140" />
				<el-table-column prop="retailPrice" label="零售价" min-width="140" sortable />
				<el-table-column prop="stockQuantity" label="库存数量" min-width="140" sortable />
				<el-table-column label="操作" width="120" fixed="right">
					<template #default="{ row }">
						<el-button type="text" @click="salesOpen(row)"> 销售 </el-button>
						<el-button type="text" @click="deleteSales(row)"> 删除 </el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页 -->
			<div class="pagination-wrapper">
				<el-pagination
					v-model:current-page="pagination.page"
					v-model:page-size="pagination.size"
					:page-sizes="[10, 20, 50, 100]"
					:total="pagination.total"
					layout="total, sizes, prev, pager, next, jumper"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>

			<!-- 销售对话框 -->
			<sales-diloag ref="SalesDiloagRef" @success="handleSaleSuccess" />
		</div>
	</el-card>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { MessageBox, Refresh, Search } from '@element-plus/icons-vue';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs';
import SalesDiloag from './component/sales-diloag.vue';

defineOptions({
	name: 'stock-product'
});

const { service } = useCool();
const { t } = useI18n();

// 响应式数据
const loading = ref(false);
const exportLoading = ref(false);
const tableData = ref<any[]>([]);
const selectedRows = ref<any[]>([]);

// 搜索表单数据
const searchForm = reactive({
	itemCode: '',
	barcode: '',
	searchKeyword: ''
});

// 分页数据
const pagination = reactive({
	page: 1,
	size: 10,
	total: 0
});

// 获取数据
const fetchData = async () => {
	loading.value = true;
	try {
		// 构建查询参数
		const params: any = {
			pageNum: pagination.page,
			pageSize: pagination.size
		};

		// 添加搜索条件
		if (searchForm.itemCode) {
			params.itemCode = searchForm.itemCode;
		}
		if (searchForm.barcode) {
			params.barcode = searchForm.barcode;
		}
		if (searchForm.searchKeyword) {
			params.searchKeyword = searchForm.searchKeyword;
		}

		const pageData = await service.ling.pageStock(params);
		if (pageData && pageData.list) {
			tableData.value = pageData.list;
			pagination.total = pageData.pagination?.total || 0;
		} else {
			tableData.value = [];
			pagination.total = 0;
		}
	} catch (error) {
		console.error('获取数据失败:', error);
		ElMessage.error('获取数据失败');
		tableData.value = [];
		pagination.total = 0;
	} finally {
		loading.value = false;
	}
};

// 刷新数据
const handleRefresh = () => {
	fetchData();
};

// 搜索
const handleSearch = () => {
	pagination.page = 1;
	fetchData();
};

// 重置搜索表单
const handleReset = () => {
	searchForm.itemCode = '';
	searchForm.barcode = '';
	searchForm.searchKeyword = '';
	pagination.page = 1;
	fetchData();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
	pagination.size = size;
	pagination.page = 1;
	fetchData();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
	pagination.page = page;
	fetchData();
};

// 选择改变
const handleSelectionChange = (selection: any[]) => {
	selectedRows.value = selection;
};

// 格式化日期
const formatDate = (date: string) => {
	if (!date) return '';
	return new Date(date).toLocaleString();
};

// 销售对话框
const SalesDiloagRef = ref();
const salesOpen = (row: any) => {
	// 映射数据格式以匹配销售对话框的期望格式
	const productData = {
		id: row.id,
		code: row.itemCode,
		name: row.name,
		price: row.retailPrice,
		quantity: row.stockQuantity
	};
	SalesDiloagRef.value.open(productData);
};

const deleteSales = async (row: any) => {
	ElMessageBox.confirm(t('确定要删除该商品吗？'), t('提示'), {
		showCancelButton: true
	})
		.then(async () => {
			try {
				await service.ling.deleteProduct({ id: row.id });
			} catch (error: any) {
				const message = error.message ? error.message : '删除失败';
				ElMessage.error(message);
				console.error('删除失败', error);
			} finally {
				fetchData();
			}
		})
		.catch(() => null);
};
// 销售成功后刷新数据
const handleSaleSuccess = () => {
	fetchData();
};

// 组件挂载时获取数据
onMounted(() => {
	fetchData();
});

const exportData = async () => {
	try {
		// 构建查询参数
		const params: any = {
			pageNum: pagination.page,
			pageSize: pagination.size
		};

		// 添加搜索条件
		if (searchForm.itemCode) {
			params.itemCode = searchForm.itemCode;
		}
		if (searchForm.barcode) {
			params.barcode = searchForm.barcode;
		}
		if (searchForm.searchKeyword) {
			params.searchKeyword = searchForm.searchKeyword;
		}

		// 调用导出接口
		exportLoading.value = true;
		const res = await service.request({
			url: '/admin/ling/exportStockProduct',
			method: 'POST',
			data: params,
			responseType: 'blob'
		});

		// 创建下载链接
		const blob = new Blob([res], {
			type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
		});

		// 生成文件名
		const fileName = `商品记录_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`;

		// 创建下载链接并触发下载
		const url = window.URL.createObjectURL(blob);
		const link = document.createElement('a');
		link.href = url;
		link.download = fileName;
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);
		window.URL.revokeObjectURL(url);

		ElMessage.success('导出成功');
	} catch (error) {
		console.error('导出失败:', error);
		ElMessage.error('导出失败，请重试');
	} finally {
		exportLoading.value = false;
	}
};
</script>

<style scoped>
.full-card {
	height: calc(100vh - 120px);
	overflow: auto;
}

.stock-product {
	padding: 20px;
}

.toolbar {
	display: flex;
	align-items: center;
	margin-bottom: 20px;
}

.flex-1 {
	flex: 1;
}

.pagination-wrapper {
	display: flex;
	justify-content: flex-end;
	margin-top: 20px;
}
</style>
